/**
 * Created by 顾杰 on 2017/3/20.
 * 文件上传组件,基于react-fileupload
 */
import React from 'react';
import FileUpload from 'react-fileupload';
import { List, Button, Toast, Icon } from 'antd-mobile';

const Item = List.Item;
const Brief = Item.Brief;
class FileUploadItem extends React.Component {

  constructor(){
    super();
    this.state={
      files: [],
      fileNames: ['请上传图片'],
      refresh: false
    }
  }

  //清空已存在数据
  componentWillReceiveProps = (nextProps) => {
    if(this.props.clear != nextProps.clear){
      this.setState({
        files: [],
        fileNames: ['请上传图片']
      })
    }
  };

  //删除所上传的文件
  removeFile = (index) => {
    //处理删除文件时中间有失败文件,对应不上情况
    let errorNum = 0;
    this.state.fileNames.map((item, i) => {
      if(i >= index) {
        return;
      }
      if(item.progress != null && item.progress == '#FF3030') {
        errorNum++;
      }
    });
    if(this.state.fileNames[index].progress == '#458B00') {
      this.state.files.splice(index-1-errorNum, 1);
    }
    this.state.fileNames.splice(index, 1);
    this.setState({
      refresh: !this.state.refresh
    });
    this.props.files(this.state.files);
  };

  //react-fileupload 所需要的参数
  getOptions = () => {
    let result = {
      //上传地址
      baseUrl: this.props.url,
      //是否选择文件后立即上传
      chooseAndUpload: true,
      //返回数据格式
      dataType : 'json',
      //限制文件类型
      accept: 'image/*',
      //选择文件
      chooseFile: (files) => {
        //不同状态的文件以不同颜色区分
        files[0].progress = '#CCCCCC';
        this.state.fileNames.push(files[0]);
        this.setState({
          refresh: !this.state.refresh
        });
        Toast.loading('上传中...', 120);
      },
      //上传成功
      uploadSuccess: (res) => {
        var item = {};
        item.path = res.data.file;
        item.size = this.state.fileNames[this.state.fileNames.length-1].size;
        item.name = this.state.fileNames[this.state.fileNames.length-1].name;
        this.state.files.push(item);
        this.state.fileNames[this.state.fileNames.length-1].progress = '#458B00';
        this.setState({
          refresh: !this.state.refresh
        });
        this.props.files(this.state.files);
        Toast.success('上传成功', 1);
      },
      //上传失败
      uploadError: (err) => {
        this.state.fileNames[this.state.fileNames.length-1].progress = '#FF3030';
        this.setState({
          refresh: !this.state.refresh
        });
        Toast.fail('上传失败,请重试', 1);
      }
    };
    return result;
  };

  render () {
    const Files = this.state.fileNames.map((item, index) => {
      if(this.state.fileNames.length == 1 && item == '请上传图片') {
        return (<div key={index}><Brief style={{float:'left'}}>请上传图片(10M之内)</Brief></div>)
      }else {
        if(item != '请上传图片'){
          //处理文件名太长情况
          let fileName = null;
          if(item.name.length >= 16) {
            fileName = item.name.substring(0, 6)+'...'+item.name.substring(item.name.length-8);
          }else{
            fileName = item.name;
          }
          return (
            <div key={index}>
              <Brief style={{float:'left', color: item.progress}}>{fileName}</Brief>
              &nbsp;&nbsp;
              <Icon size="xs" value={index} type="cross" color="#bbb" style={{marginTop: '0.2rem'}} onClick={() => this.removeFile(index)}/>
            </div>
          )
        }
      }
    });

    return (
      <div>
        <List renderHeader={() => this.props.listTitle ? this.props.listTitle : '附件'}>
          <Item
            multipleLine
            extra={
                <FileUpload options={this.getOptions()}>
                  <Button style={{marginTop: '25%'}} type="ghost" size="small" ref="chooseAndUpload" inline>上传</Button>
                </FileUpload>
              }
          >
            {Files}
          </Item>
        </List>
      </div>
    );
  }
}

export default FileUploadItem;
